package com.melody.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.melody.entry.Result;
import com.melody.model.vo.MusicSearchVo;
import com.melody.model.vo.PlaylistSearchVo;
import com.melody.service.MusicSearchService;
import com.melody.service.PlaylistSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
/**
 * @Author: hq
 * @Description: 搜索功能
 * @DateTime: 2025-05-12 21:58
 **/
@RestController
@RequestMapping("/search")
public class MusicSearchController {

    @Autowired
    private MusicSearchService musicSearchService;

    @Autowired
    private PlaylistSearchService playlistSearchService;

    /**
     * 搜索歌曲功能
     */
    @GetMapping("/music")
    public Result<?> searchMusic(@RequestParam String keyword,
                                 @RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "10") int limit) {
        try {
            // 创建分页对象
            Page<MusicSearchVo> musicSearchPage = new Page<>(page, limit);
            // 调用服务层方法
            Page<MusicSearchVo> results = musicSearchService.searchMusic(keyword, musicSearchPage);

            if (results.getRecords().isEmpty()) {
                return Result.error("搜索失败");
            }
            // 创建一个Map来存储分页信息和数据
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("currentPage", results.getCurrent());
            dataMap.put("totalPages", results.getPages());
            dataMap.put("totalRecords", results.getTotal());
            dataMap.put("records", results.getRecords());

            return Result.success(dataMap);
        } catch (Exception e) {
            return Result.error("搜索失败");
        }
    }

    /**
     * 搜索歌单功能
     */
    @GetMapping("/playlist")
    public Result<?> searchPlaylist(@RequestParam String keyword,
                                    @RequestParam(defaultValue = "1") int page,
                                    @RequestParam(defaultValue = "10") int limit) {
        try {
            // 创建分页对象
            Page<PlaylistSearchVo> playlistSearchPage = new Page<>(page, limit);
            // 调用服务层方法
            Page<PlaylistSearchVo> results = playlistSearchService.searchPlaylist(keyword, playlistSearchPage);

            if (results.getRecords().isEmpty()) {
                return Result.error("搜索失败");
            }
            // 创建一个Map来存储分页信息和数据
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("currentPage", results.getCurrent());
            dataMap.put("totalPages", results.getPages());
            dataMap.put("totalRecords", results.getTotal());
            dataMap.put("records", results.getRecords());
            return Result.success(dataMap);
        } catch (Exception e) {
            return Result.error("搜索失败");
        }
    }
}
